package com.imist.servlet;

import com.imist.data.Cart;
import com.imist.data.LocalCache;
import com.imist.data.Product;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

public class CartServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String servletPath = req.getServletPath();//获取请求的URl一般在servlet里面使用
        String contextPath = req.getContextPath();//获取工程路径一般在jsp页面获取资源的时候使用
        if (Objects.equals("/cart/cart.do",servletPath)){
            //页面传入的参数没有类型，String
            String productId = req.getParameter("productId");
            if (null != productId){
                Product product = LocalCache.getProduct(Long.valueOf(productId));
                LocalCache.addCart(product);
            }
            resp.sendRedirect("/cart/list.do");
        }else if (Objects.equals("/cart/list.do",servletPath)){
            req.setAttribute("carts",LocalCache.getCarts());
            //这里注意路径
            req.getRequestDispatcher("/WEB-INF/views/biz/cart.jsp").forward(req,resp);
        }else if(Objects.equals("/cart/delete.do",servletPath)){
            String productId = req.getParameter("productId");
            if (null != productId){
                LocalCache.delCart(Long.valueOf(productId));
            }
            resp.sendRedirect("/cart/list.do");
        }else if(Objects.equals("/cart/incr.do",servletPath)){
            String productId = req.getParameter("productId");
            if (null != productId){
                LocalCache.incrCart(Long.valueOf(productId));
            }
            resp.sendRedirect("/cart/list.do");
        }else if (Objects.equals("/cart/decr.do",servletPath)){
            String productId = req.getParameter("productId");
            if (null != productId){
                LocalCache.dercCart(Long.valueOf(productId));
            }
            resp.sendRedirect("/cart/list.do");
        }else if (Objects.equals("/cart/settlement.do",servletPath)){
            //获取页面name为carts 的所有值，也就是购物车Id的集合
            String[] cartIds = req.getParameterValues("carts");
            int totalPrice = 0;
            for (String cartId : cartIds) {
                Cart cart = LocalCache.getCart(Long.valueOf(cartId));
                totalPrice += cart.getTotalPrice();
                LocalCache.delCart(cart.getId());
            }
            req.setAttribute("totalPrice",totalPrice);
            req.getRequestDispatcher("/WEB-INF/views/biz/settlement.jsp?").forward(req,resp);
        }
    }
}
